<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @package         925CMS
 * @subpackage         WYSIWYG
 * @author            Phil Sturgeon, HoangNQ, Marcos Coelho
 *
 * Manages image selection and insertion for WYSIWYG editors
 */
class Image_Popup extends Admin_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->template
                ->set_theme(ADMIN_THEME)
                ->set_layout('modal', 'admin')
                ->append_metadata(css('wysiwyg.css', 'wysiwyg'))
                ->append_metadata(js('jquery/jquery.livequery.min.js'))
                ->append_metadata(js('wysiwyg_popup.js', 'wysiwyg'))
                ->append_metadata(css('jquery/uniform.default.css'))
                ->append_metadata(js('jquery/jquery.uniform.min.js'))
                ->append_metadata(js('jquery/jquery.colorbox.min.js'));
        $this->load->model(array('libs/file_m', 'libs/libraries_m'));
        $this->lang->load('libs/libraries');
        $this->lang->load('wysiwyg');
    }

    public function index($id = 0)
    {
        /** @var $data obj */
        $data->libraries = $this->libraries_m->get_libraries();
        $data->sublibraries = array();
        $data->current_library = $id && isset($data->libraries[$id])
                ? $data->libraries[$id]
                : ($data->libraries ? current($data->libraries) : array());

        if ($data->current_library) {
            $data->current_library->items = $this->file_m
                    ->order_by('date_added', 'DESC')
                    ->where('type', 'i')
                    ->get_many_by('library_id', $data->current_library->id);

            $sublibraries = $this->libraries_m->library_tree($data->current_library->id);

            foreach ($sublibraries as $sublirary)
            {
                $data->sublibraries[$sublirary->id] = repeater('&raquo; ', $sublirary->depth) . $sublirary->name;
            }

            // Set a default label
            $data->sublibraries = $data->sublibraries
                    ? array($data->current_library->id => lang('files.dropdown_root')) + $data->sublibraries
                    : array($data->current_library->id => lang('files.dropdown_no_subfolders'));
        }

        // Array for select
        $data->libraries_tree = array();
        foreach ($data->libraries as $library)
        {
            $data->libraries_tree[$library->id] = repeater('&raquo; ', $library->depth) . $library->title;
        }
        $this->template
                ->title('Images')
                ->build('image_popup/index', $data);
    }

}